export const CodeCollapse = {
  props: {
    codes: { type: Array, required: true }
  },

  data() {
    return {
      inited: false,
      activeName: [],
      scrollTop: 0
    }
  },

  template: `
  <el-collapse v-model="activeName" style="margin-top: 25px" @change="onChange">
    <el-collapse-item :title="activeName.length > 0 ? '收起代码' : '查看代码'" name="1" ref="container">
      <pre
        v-for="(code, index) in codes"
        :key="index"
        :style="index === codes.length - 1 ? '' : 'margin-top: 15px'"
      >
        <code>{{ code }}</code>
      </pre>
      <i class="el-icon-caret-top" title="关闭" @click="close" />
    </el-collapse-item>
  </el-collapse>
  `,

  methods: {
    onChange(val) {
      if (val) {
        this.scrollTop = document.documentElement.scrollTop
      }

      if (!this.inited) {
        this.inited = true
        this.$nextTick(() => {
          this.$refs.container.$el.querySelectorAll('pre code').forEach((el) => {
            window.hljs.highlightElement(el);
          });
        })
      }
    },
    close() {
      this.activeName = []
      this.$nextTick(() => {
        document.documentElement.scrollTop = this.scrollTop
      })
    }
  }
}